<?php

namespace app\models;

use yii;
use yii\db\Query;

class Modules extends BaseModel
{
    use \app\lib\Redis;

    private $redis;

    public function __construct()
    {
        $this->table = yii::$app->db->tablePrefix . 'modules';
        $this->redis = $this->getInstance();
    }

    public function all($where = [], $offset = false, $limit = false, $order = false)
    {
        if ($list = $this->redis->get('module:all')) {
            return json_decode($list, true);
        }
        $db = new Query();
        $list = $db->select('*')->from($this->table)->all();
        $this->redis->setex('module:all', 3600, json_encode($list));
        return $list;
    }

    public function one($where = [])
    {

    }


    public function get_left_nav($module_id)
    {
        $db = new Query();
        //获取二级目录
        $list = $db->select('*')
            ->from(yii::$app->db->tablePrefix . 'modules')
            ->where(['pid' => $module_id, 'module' => 2])
            ->all();

        $arr = [];
        foreach ($list as $v) {
            $arr[] = $v['id'];
        }
        $db2 = new Query();
        $list2 = $db2->select('*')
            ->from(yii::$app->db->tablePrefix . 'modules')
            ->where(['in', 'pid', $arr])
            ->andWhere(['module' => 3])
            ->all();
        $data = ["level2" => $list, 'level3' => $list2];
        return $data;
    }

    public function get_all_action_list()
    {
        return (new \yii\db\Query)->select('*')
            ->from(yii::$app->db->tablePrefix . "modules")
            ->orderBy(['pid' => SORT_ASC, 'order_id' => SORT_ASC])
            ->all();
    }

    public function get_action_by_id($id)
    {
        return (new \yii\db\Query)->select('*')
            ->from(yii::$app->db->tablePrefix . "modules")
            ->where(['id' => $id])
            ->one();
    }

    public function update_rule_by_role($role, $rules)
    {
        return yii::$app->db->createCommand()
            ->update(yii::$app->db->tablePrefix . "adminrole", ['role_rules' => $rules], ['id' => $role])
            ->execute();
    }

    public function get_url_info($url)
    {
        $db = new yii\db\Query();
        return $db->select('*')
            ->from(yii::$app->db->tablePrefix . 'modules')
            ->where(['url' => $url])
            ->one();
    }
}
